﻿const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const _ = db.command; 

const normalizeString = (value) => (typeof value === 'string' ? value.trim() : '');

// 将任意可能的 id 值统一为字符串，便于稳定比对
const toStrId = (raw) => (raw == null ? '' : String(raw));

exports.main = async (event, context) => {
  try {
    const wxContext = cloud.getWXContext();
    const operatorOpenID = wxContext.OPENID;
    const activityID = normalizeString(event.activityID);
    const targetOpenID = normalizeString(event.targetOpenID);

    if (!operatorOpenID) {
      return { success: false, error: '未获取到用户信息' };
    }
    if (!activityID) {
      return { success: false, error: '缺少活动编号' };
    }

    // 默认查询操作者自己的信息；若指定 targetOpenID，则校验是否是发布者
    let queryOpenID = operatorOpenID;

    if (targetOpenID && targetOpenID !== operatorOpenID) {
      const activityDoc = await db
        .collection('Activity_Information')
        .doc(activityID)
        .get()
        .catch(() => null);

      if (!activityDoc || !activityDoc.data) {
        return { success: false, error: '未找到活动信息' };
      }
      if (activityDoc.data.PublisherOpenID !== operatorOpenID) {
        return { success: false, error: '无权查看该报名信息' };
      }
      queryOpenID = targetOpenID;
    }

    // 基础资料
    const userRes = await db
      .collection('User_Profile')
      .where({ OpenID: queryOpenID })
      .limit(1)
      .get();

    if (!userRes.data || userRes.data.length === 0) {
      return { success: false, error: '未找到用户资料' };
    }

    const user = userRes.data[0];
    const result = {
      name: user.Name || '',
      gender: user.Gender || '',
      studentID: user.StudentID || '',
      studentType: user.StudentType || '',
      grade: user.EnrollmentYear || '',
      college: user.College || '',
      major: user.Major || '',
      phoneNumber: user.PhoneNumber || '',
      registrationGroups: [],
      registrationFields: [],
    };

    // 已报名的分组信息
    const groupDocs = await db
      .collection('Activity_Group_Information')
      .where({ ActivityID: activityID })
      .get();

    const groupMetaMap = new Map();
    const groupIDs = Array.isArray(groupDocs.data)
      ? groupDocs.data.map((item) => {
          groupMetaMap.set(item._id, item);
          return item._id;
        })
      : [];

    if (groupIDs.length > 0) {
      const registrationRes = await db
        .collection('Group_Registration_Information')
        .where({
          OpenID: queryOpenID,
          GroupID: _.in(groupIDs),
        })
        .get();

      result.registrationGroups = Array.isArray(registrationRes.data)
        ? registrationRes.data.map((record) => {
            const meta = groupMetaMap.get(record.GroupID) || {};
            const startSource =
              record.GroupStartTime ||
              (record.GroupTime && record.GroupTime.start) ||
              meta.GroupStartTime ||
              null;
            const endSource =
              record.GroupEndTime ||
              (record.GroupTime && record.GroupTime.end) ||
              meta.GroupEndTime ||
              null;
            return {
              GroupID: record.GroupID,
              GroupStartTime: startSource,
              GroupEndTime: endSource,
              GroupName: meta.GroupName || '',
            };
          })
        : [];
    }

    // 活动定义的“需要收集的字段”
    const fieldDocs = await db
      .collection('Activity_Registration_Information_Fields')
      .where({ ActivityID: activityID })
      .get();

    const fields = Array.isArray(fieldDocs.data) ? fieldDocs.data : [];

    //建立 id->name映射
    const fieldMap = new Map();
    const fieldIDs = fields
      .map((f) => {
        const rawId = f.FieldID ?? f.fieldId ?? f.FieldId ?? f._id;
        const id = toStrId(rawId);
        if (id) {
          const name = f.FieldName ?? f.fieldName ?? '';
          fieldMap.set(id, name);
        }
        return id;
      })
      .filter(Boolean);
    if (fieldIDs.length > 0) {
      const allByUser = await db
        .collection('Group_Registration_Custom_Fields')
        .where({ OpenID: queryOpenID })
        .get();

      const items = Array.isArray(allByUser.data) ? allByUser.data : [];
      const idSet = new Set(fieldIDs);

      const filtered = items.filter((it) => {
        const raw = it.FieldID ?? it.fieldId ?? it.FieldId;
        return raw != null && idSet.has(toStrId(raw));
      });

      result.registrationFields = filtered.map((item) => {
        const id = toStrId(item.FieldID ?? item.fieldId ?? item.FieldId);
        return {
          fieldID: id,
          fieldName: fieldMap.get(id) || '',
          fieldContent: item.FieldContent ?? item.content ?? '',
        };
      });
    }

    return { success: true, data: result };
  } catch (error) {
    console.error('queryRegistrationInfo error', error);
    return { success: false, error: '查询失败，请稍后重试' };
  }
};
